package com.ssm.handler;

import com.ssm.utils.Base64Util;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 给手机号进行加密解密的处理类
 */
public class MobileHandler implements TypeHandler<String> {
    private Logger logger = Logger.getLogger(MobileHandler.class);
    /**
     * 给参数s进行加密
     * @param preparedStatement
     * @param i
     * @param s
     * @param jdbcType
     * @throws SQLException
     */
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, String s, JdbcType jdbcType) throws SQLException {
        if(s != null){
            String encryptBase64Phone = Base64Util.encryptBase64(s.getBytes());
            logger.info("手机号："+s+"--加密为---> "+ encryptBase64Phone);
            preparedStatement.setString(i,encryptBase64Phone);
        }

    }

    /**
     * 给参数s进行解密
     * @param resultSet
     * @param s
     * @return
     * @throws SQLException
     */
    @Override
    public String getResult(ResultSet resultSet, String s) throws SQLException {

        String phone = resultSet.getString(s);
        String phoneRegex = "^1[3-9]\\d{9}$";
        if(phone != null){
            boolean matches = phone.matches(phoneRegex);
            if (matches){
                logger.info("手机号码格式正确");
                return phone;
            }
            try {
                String decryPhone = Base64Util.decryBase64(phone);
                logger.info("手机号："+s+"--jie密为---> "+ decryPhone);
                return decryPhone;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public String getResult(ResultSet resultSet, int i) throws SQLException {
        String string = resultSet.getString(i);
        if(string!=null){
            try{
                String s1 = Base64Util.decryBase64(string).toString();
                return s1;
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public String getResult(CallableStatement callableStatement, int i) throws SQLException {
        String string = callableStatement.getString(i);
        if(string!=null){
            try{
                String s1 = Base64Util.decryBase64(string).toString();
                return s1;
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return null;
    }
}
